package com.ns.dcjh.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.kwai.opensdk.sdk.constants.KwaiPlatform;
import com.kwai.opensdk.sdk.model.base.BaseResp;
import com.kwai.opensdk.sdk.model.base.OpenSdkConfig;
import com.kwai.opensdk.sdk.model.postshare.MultiMediaClip;
import com.kwai.opensdk.sdk.model.postshare.MultiPictureEdit;
import com.kwai.opensdk.sdk.model.postshare.PostShareMediaInfo;
import com.kwai.opensdk.sdk.model.postshare.SingleVideoEdit;
import com.kwai.opensdk.sdk.openapi.IKwaiAPIEventListener;
import com.kwai.opensdk.sdk.openapi.IKwaiOpenAPI;
import com.kwai.opensdk.sdk.openapi.KwaiOpenAPI;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.ns.dcjh.bean.MessageEvent;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.vo.KuaiShouInfoVo;
import com.orhanobut.logger.Logger;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class KuaiShouUtils {

    private final Context mContext;

    private final IKwaiOpenAPI mKwaiOpenAPI;


    public KuaiShouUtils(Context context) {
        this.mContext = context;
        mKwaiOpenAPI = new KwaiOpenAPI(context);
        // 设置平台功能的配置选项
        OpenSdkConfig openSdkConfig = new OpenSdkConfig.Builder()
                .setGoToMargetAppNotInstall(false) // 应用未安装，是否自动跳转应用市场
                .setGoToMargetAppVersionNotSupport(false) // 应用已安装但版本不支持，是否自动跳转应用市场
                .setSetNewTaskFlag(true) // 设置启动功能页面是否使用新的页面栈
                .setSetClearTaskFlag(false) // 设置启动功能页面是否清除当前页面栈，当isSetNewTaskFlag为true时生效
                .setShowDefaultLoading(false) // 是否显示默认的loading页面作为功能启动的过渡
                .build();
        mKwaiOpenAPI.setOpenSdkConfig(openSdkConfig);

        // 业务请求回调结果监听
        mKwaiOpenAPI.addKwaiAPIEventListerer(new IKwaiAPIEventListener() {

            @Override
            public void onRespResult(@NonNull BaseResp resp) {
                Log.i("TAG", "resp=" + resp);
                Log.i("TAG", "errorCode=" + resp.errorCode + ", errorMsg="
                        + resp.errorMsg + ", cmd=" + resp.getCommand()
                        + ", transaction=" + resp.transaction + ", platform=" + resp.platform);
                JSONObject extras = new JSONObject();
                extras.put("errorCode", resp.errorCode);
                extras.put("errorMsg", kuaishouErrorMsg(resp.errorCode));

                MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_SHARE_KUAISHOU_RESP);
                msgEvent.setExtras(extras);
                EventBus.getDefault().post(msgEvent);

                mKwaiOpenAPI.removeKwaiAPIEventListerer();
            }
        });
    }

    public String kuaishouErrorMsg(int errorCode) {
        switch (errorCode) {
            case 1:
                return "分享成功";
            case -1:
                return "内部问题，联系客服";
            case -1005:
                return "没有安装快手App";
            case -1006:
                return "不支持此功能";
            case -1010:
                return "参数传递失败";
            case -1011:
                return "快手App没有登录";
            case -1013:
                return "拒绝当次分享动作；如果是发布视频，请检查视频长度；mDisableFallback是否是false";
            case -1014:
                return "快手App开着青少年模式，关闭即可";
            case -1015:
                return "网络出现异常，可以稍后试试";
            case -1016:
                return "快手App没有存储权限";
            case -1017:
                return "分享的图片损坏";
            case -1018:
                return "3s内不能重复分享";
            case -1019:
                return "视频size太大";
            default:
                return "未知分享结果";
        }
    }

    //分享
    public void share(KuaiShouInfoVo vo) {

        if (vo.isUseImgs()) {
            if (vo.getImgs() == null || vo.getImgs().isEmpty()) {
                ToastUtils.info(mContext, "请至少选择一张图片");
                return;
            }

            ArrayList<Bitmap> bitmapList = new ArrayList<>();

            for (Object object : vo.getImgs()) {
                try {
                    String image = (String) object;
                    String[] imageSplit = image.split(",");
                    if (imageSplit.length < 2) continue;
                    Bitmap bitmap = BitmapUtils.base64ToBitmap(imageSplit[1], mContext);
                    bitmapList.add(bitmap);
                } catch (Exception e) {
                    ToastUtils.info(mContext, e.getMessage());
                }
            }
            ArrayList<String> imageList = new ArrayList<>();

            BitmapUtils.bitmapSaveFileToStorage(bitmapList).subscribe(new Observer<File>() {
                @Override
                public void onSubscribe(Disposable d) {
                }

                @Override
                public void onNext(File file) {
                    imageList.add(file.getAbsolutePath());
                    Log.e("TAG", "onNext: " + file.getAbsolutePath());
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {
                    if (!imageList.isEmpty()) {
                        if (vo.getEdit_type() == null || vo.getEdit_type().isEmpty() || vo.getEdit_type().equals("multi_media_clip")) {
                            shareImageClip(imageList, vo.getTag());
                        } else if (vo.getEdit_type().equals("multi_pic_edit")) {
                            shareImagesEdit(imageList, vo.getTag());
                        }

                    }
                }
            });

        } else {
            startDownloadVideo(vo);
        }

    }

    private void startDownloadVideo(KuaiShouInfoVo vo) {
        String video = StringUtils.isEmpty(vo.getVideo()) ? vo.getVideoNb() : vo.getVideo();
        if (StringUtils.isEmpty(video)) {
            ToastUtils.info(mContext, "无效的视频地址");
            return;
        }

        File file = FileUtils.getFile("video", "mp4");

        LoadingUtils mLoading = LoadingUtils.create(mContext).show();
        FileDownloader
                .getImpl()
                .create(video)
                .setPath(file.getAbsolutePath())
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        mLoading.dismiss();
                        shareVideo(file.getAbsolutePath(), vo.getTag());
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        mLoading.dismiss();
                        Logger.d("下载视频失败");
                        vo.setVideo(vo.getVideoNb());
                        if (!StringUtils.equals(vo.getVideo(), vo.getVideoNb())) {
                            startDownloadVideo(vo);
                        } else {
                            ToastUtils.info(mContext, "下载视频失败");
                        }
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        mLoading.dismiss();
                    }
                })
                .start();

    }


    //分享照片
    private void shareImagesEdit(ArrayList<String> imageList, String tag) {
        MultiPictureEdit.Req req = new MultiPictureEdit.Req();
        req.sessionId = mKwaiOpenAPI.getOpenAPISessionId();
        req.transaction = "MultiPictureEdit";
        req.setPlatformArray(new String[]{KwaiPlatform.Platform.KWAI_APP});
        req.mediaInfo = new PostShareMediaInfo();

        ArrayList<String> imageFiles = new ArrayList<>();
        for (String item : imageList) {
            String fileUriPath = FileProviderUtil.generateFileUriPath((Activity) mContext, new File(item), req,
                    mKwaiOpenAPI);
            imageFiles.add(fileUriPath);
        }

        req.mediaInfo.mMultiMediaAssets = imageFiles;
        printShareFilePath(req.mediaInfo.mMultiMediaAssets);
        req.mediaInfo.mTag = tag;

        req.mediaInfo.mDisableFallback = false;
        // 检查快手版本是否支持多图编辑
        if (mKwaiOpenAPI.isAppSupportEditMultiPicture(mContext, req)) {
            mKwaiOpenAPI.sendReq(req, (Activity) mContext);
        } else {
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.info(mContext, "快手版本不支持多图编辑，请更新快手");
                }
            });
        }
    }

    private void shareImageClip(ArrayList<String> imageList, String tag) {
        MultiMediaClip.Req req = new MultiMediaClip.Req();
        req.sessionId = mKwaiOpenAPI.getOpenAPISessionId();
        req.transaction = "MultiMediaClip";
        // 设置功能调起快手支持应用，KwaiPlatform.Platform.KWAI_APP（快手主站），KwaiPlatform.Platform.NEBULA_APP（快手极速版）
        // 按数组顺序检查应用安装和版本情况，从中选择满足条件的第一个应用调起，若不设置则默认启动快手主站应用
        req.setPlatformArray(new String[]{KwaiPlatform.Platform.KWAI_APP});

        ArrayList<String> imageFiles = new ArrayList<>();
        for (String item : imageList) {
            String fileUriPath = FileProviderUtil.generateFileUriPath((Activity) mContext, new File(item), req,
                    mKwaiOpenAPI);
            imageFiles.add(fileUriPath);
        }
        req.mediaInfo = new PostShareMediaInfo();
        req.mediaInfo.mMultiMediaAssets = imageFiles;
        req.mediaInfo.mTag = tag;
        req.mediaInfo.mDisableFallback = false;
        if (mKwaiOpenAPI.isAppSupportEditMultiPicture(mContext, req)) {
            mKwaiOpenAPI.sendReq(req, (Activity) mContext);
        } else {
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.info(mContext, "快手版本不支持图文分享，请更新快手");
                }
            });
        }
    }

    private void shareVideo(String video, String tag) {
        SingleVideoEdit.Req req = new SingleVideoEdit.Req();
        req.sessionId = mKwaiOpenAPI.getOpenAPISessionId();
        req.transaction = "SingleVideoEdit";
        // 设置功能调起快手支持应用，KwaiPlatform.Platform.KWAI_APP（快手主站），KwaiPlatform.Platform.NEBULA_APP（快手极速版）
        // 按数组顺序检查应用安装和版本情况，从中选择满足条件的第一个应用调起，若不设置则默认启动快手主站应用
        req.setPlatformArray(new String[]{KwaiPlatform.Platform.KWAI_APP});
        req.mediaInfo = new PostShareMediaInfo();
        ArrayList<String> videoFiles = new ArrayList<>();
        String fileUriPath = FileProviderUtil.generateFileUriPath((Activity) mContext, new File(video), req,
                mKwaiOpenAPI);
        videoFiles.add(fileUriPath);
        req.mediaInfo.mMultiMediaAssets = videoFiles;
        printShareFilePath(req.mediaInfo.mMultiMediaAssets);
        req.mediaInfo.mTag = tag;

        req.mediaInfo.mDisableFallback = false;

        if (mKwaiOpenAPI.isAppSupportEditMultiPicture(mContext, req)) {
            mKwaiOpenAPI.sendReq(req, (Activity) mContext);
        } else {
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.info(mContext, "快手版本不支持视频分享，请更新快手");
                }
            });
        }
    }


    private void printShareFilePath(ArrayList<String> pathList) {
        for (String item : pathList) {
            Log.d("TAG", "path is " + item);
        }
    }

}
